﻿using UnityEngine;
using System.Collections;

public class NGUITweenValue :MonoBehaviour {
	public FSM FSMValue;
	public delegate void callback (float value);
	public event callback OnValueChange;
	StatePath idle = new StatePath("m_Idle");
	StatePath update = new StatePath("m_Updateing");
	float m_target;
	float m_value;
	float m_UpdateSpeed;
	bool m_UseInt;
	bool m_UseLerp;
	void Awake(){
		FSMValue = new FSM ();
		FSMValue.AddState (idle,OnIdleEnter,OnIdleUpdate);
		FSMValue.AddState (update,OnUpdateEnter,OnUpdateIng);
	}
	void Update(){
		FSMValue.UpdateState (Time.deltaTime);
	}
	public float SetValueNow{
		set{
			m_target = value;
			m_value = value;
			FSMValue.SetState(idle);
		}
	}
	public bool UseLerp{
		set{ m_UseLerp = value;}
	}
	public bool UseInt{
		set{ m_UseInt = value;}
	}
	public float Value{
		get{
			if (m_UseInt)
				return (int)m_value;
			else
				return m_value;
		}
		set{
			m_value = value;
			if(m_UseInt)
				ValueChange((int)m_value);
			else
				ValueChange(m_value);
		}
	}
	public virtual void ValueChange(float f){
		if(OnValueChange!=null)
			OnValueChange(f);
	}
	public float SetUpdateSpeed{
		set{ m_UpdateSpeed = value;}
	}
	public float TargetValue{
		get{return m_target;}
		set{
			if(m_target != value){
				m_target = value;
				FSMValue.SetState(update);
			}
		}
	}
	void OnIdleEnter(){
	}
	void OnIdleUpdate(float dt){

	}
	float startt;
	float speed;
	void OnUpdateEnter(){
		startt = Time.time;
	}
	void OnUpdateIng(float dt){
		if (m_value != m_target) {
			if(m_UseLerp){
				Value = Mathf.Lerp(m_value,m_target,(Time.time - startt)/ m_UpdateSpeed);
				if(Value == m_target)
					FSMValue.SetState(idle);
			}
			else{
				int dir;
				float newvalue;
				dir = m_value < m_target ? 1:-1;
				newvalue = m_value+dt*m_UpdateSpeed*dir;
				if(dir == 1){
					if(newvalue > m_target)
						newvalue = m_target;
				}
				else{
					if(newvalue < m_target)
						newvalue = m_target;
				}
				Value = newvalue;
				if((dir == 1 && m_value > m_target) || (dir == -1 && m_value < m_target)){
					FSMValue.SetState(idle);
				}
			}
		}
	}
}

